Ext.define('appmod.controller.file.Startup', {
    extend: 'Ext.app.Controller',

    views: [
    	'user.DefaultListView',
		'user.FileForm',
		'user.FileEditingForm',
		'user.FileRoleSelectedForm'
    ],
	models : [
		'file.File'
	],
	
    stores: [
		'file.Fit',
		'role.AllAvailable'
	],	

    refs: [
		{ref: 'defaultListView',selector:'defaultlistview'},
		{ref: 'searchListView',selector:'defaultlistview searchfield'},
		{ref:'userRoleSelectedForm' , selector:'userroleselectedform'},
		{ref:'userForm' , selector:'userform'},
		{ref:'updateFormButton' , selector:'window button[action=updateUserAccount]'},
		{ref:'addFormButton' , selector:'window button[action=addUserAccount]'}
		

	],

    init: function() {

    	this.control({
			'defaultlistview menuitem[action=addsimpleuser]': {
				click:this.showAddSimpleUserInfoForm
			},
			'defaultlistview menuitem[action=updatesimpleuser]': {
				click:this.showUpdateSimpleUserInfoForm
			},			
			'defaultlistview menuitem[action=selectroles]': {
				click:this.showSelectRolesform
			},
			'defaultlistview menuitem[action=deleteusers]': {
				click:this.showDeleteusersDialog
			}
			
						

    	});


    },
	
		
	loadInitComp : function() {
		var mainPanel = Ext.create('appmod.view.file.DefaultListView' , {
			region : 'center',
			border:false,
			padding:'0 0 0 0'
		});
		return mainPanel;		
	},
	
	onLaunch:function(app) {
		
		var me = this;
		
		var defListView = me.getDefaultListView();
		var dsUserPange = me.getUserPagingStore();
		
		defListView.bindStore( dsUserPange );
		
	},
	
	// create dinfoe
	showAddSimpleUserInfoForm : function() {
		var me = this;
		var win = null;
		// --- build new form ---
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '系统帐号信息',
				closable : true,
				//closeAction:'hide',
				modal:true,
				width : 450,
				height : 480,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'userform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'addUserAccount'
        				},{
            				text: '重 置',
							action:'reset'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("userform");

		var saveBtn = win.down('button[action="addUserAccount"]');
		saveBtn.on("click",me.saveNewUser , me , {
			window : win
		});

		if ( !win.isVisible() ) {
			win.show();
		}
		
	},
	
	saveNewUser:function(btn , event , eOpts) {
		var me = this;
		var listView = me.getDefaultListView();
		var dsUser = listView.getStore();

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('userform');
		var win = upWin;
		
		var form = formPanel.getForm();
		form.submit({
			url:'../../data/resource/user/submit_adding.json',
			success:function(form , action) {
				 // --- reflash store ---
				 win.close();
				 
				 dsUser.load();
				 
				 Ext.Msg.alert('成功', action.result.msg);
			},
			failure: function(form, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});
	},
	
	// create user info
	showUpdateSimpleUserInfoForm : function() {

		var me = this;
		var defListView = me.getDefaultListView();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();

		if (rec.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个帐号',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		} else if (rec.length  > 1) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '只能选择一个帐号',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}
		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '系统帐号信息',
				mark:'userform',
				closable : true,
				modal:true,
				//closeAction:'hide',
				width : 450,
				height : 380,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'user.editingform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'updateUserAccount'
        				},{
            				text: '重 置',
							action:'reset'
        				}
				    ]
				}]	
			});
		}

		var formPanel = win.down("user-editingform");

		var saveBtn = win.down('button[action="updateUserAccount"]');
		saveBtn.on("click",me.saveUpdateUser , me , {
			window : win
		});

		// --- init form data ---
		var form = formPanel.getForm();
		
		form.load({
			params:{
				userId:rec[0].getId()
			},
			url: '../../data/resource/user/load_simpleuser.json',
            waitMsg: '数据加载中'			
		});
		

		
		if ( !win.isVisible() ) {
			win.show();			
		}		
	},
	
	saveUpdateUser:function(btn , event , eOpts) {
		var me = this;
		var listView = me.getDefaultListView();
		var dsUser = listView.getStore();

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('user-editingform');
		var win = upWin;
		
		var form = formPanel.getForm();
		form.submit({
			url:'../../data/resource/user/submit_updating.json',
			success:function(form , action) {
				 // --- reflash store ---
				 win.close();
				 
				 dsUser.load();
				 
				 Ext.Msg.alert('成功', action.result.msg);
			},
			failure: function(form, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});
	},
	
		
	showSelectRolesform:function() {
		
		var me = this;
		
		var defListView = me.getDefaultListView();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();

		if (rec.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个帐号',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		} else if (rec.length  > 1) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '只能选择一个帐号',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}
		
		var dsRoleIds = me.getRoleAllAvailableStore();
		dsRoleIds.reload();
	

		var fieldStores = {
			'dsRoleIds' : dsRoleIds
		};
				
		
		var win = null;
		// --- build new form ---
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '选择角色',
				mark : 'user.roleselectedform',
				closable : true,
				modal:true,
				//closeAction:'hide',
				width : 500,
				height : 450,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					defaults: {
        				labelWidth:65
    				},
					fieldStores:fieldStores,
					xtype : 'user.roleselectedform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
							xtype: 'button',
							text: '保存更新',
							action:'saveSelectedRole'
						}
				    ]
				}]				

			});
		}
		
		// --- init form data ---
		var formPanel = win.down("user-roleselectedform");

		var saveBtn = win.down('button[action="saveSelectedRole"]');
		saveBtn.on("click",me.updateSelectedRoles , me , {
			window : win
		});
		
		// ---- load available event ---
		
		var form = formPanel.getForm();		
		form.load({
			params:{
				userId:rec[0].getId()
			},
			url: '../../data/resource/user/role/load_assigned.json',
            waitMsg: '数据加载中'			
		});
	


		// --- load and init object value ---
		if ( rec.length == 1 ) {
			
			form.setValues({
				name:rec[0].get('name'),
				id:rec[0].getId()
			});
			
		}
		
		if ( !win.isVisible() ) {
			win.show();
		}			
	},
	
	updateSelectedRoles:function(btn , event , eOpts) {
		var me = this;
		var listView = me.getDefaultListView();
		var dsUser = listView.getStore();

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('user-roleselectedform');
		var win = upWin;
		
		var form = formPanel.getForm();
		form.submit({
			url:'../../data/resource/user/role/submit_assign.json',
			success:function(form , action) {
				 // --- reflash store ---
				 win.close();
				 
				 dsUser.load();
				 
				 Ext.Msg.alert('成功', action.result.msg);
			},
			failure: function(form, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});		
	},
	
	
	showDeleteusersDialog:function() {
		var me = this;
		
		var defListView = me.getDefaultListView();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();


		if (rec.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个帐号',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}
		
		// --- select resource --
		var removeRecs = "";
		for (var i = 0 ; i < rec.length ; i++) {
			if (removeRecs.length != 0 ) {
				removeRecs += ",";
			}
			removeRecs += rec[i].get('name');
		}
		
		Ext.MessageBox.confirm('确认', '肯定要删除帐号: "'+removeRecs+'"?',me.confirmDeletedUsers , me);
	},
	
	confirmDeletedUsers:function(confirm , other) {

		var me = this;
		
		var defListView = me.getDefaultListView();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();
		
		if (confirm == "no") {
			return;
		}

		var jsonObj = [];
		for (var i = 0 ; i < rec.length ; i++) {
			jsonObj.push(rec[i].getId());
		}

		
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../../data/resource/user/submit_deleteall.json',
				method:'post',
				/*
				params:{
					'jsonData':Ext.encode(jsonObj)
				},
				*/
				jsonData:jsonObj,
				success: function(response, opts) {

					var listView = me.getDefaultListView();
					// --- update load ---
					listView.getStore().load();
										 
     				var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---

				},
				failure: function(response, opts) {
				
				}
			});

			
		} catch (e) {
			alert(e);
		}	
		
	}

	
	
});